<template>
  <div class="content-container">
    
    <!-- 工具栏 -->
    <!-- <div ref="adminContentTools" class="content-tools-wrap hidden">
      	<div class="tools-left f-l">
      		
      		<el-button-group>
             <el-button type="primary" @click="handleAdd">新增设备</el-button>
			   </el-button-group>

      	</div>
      	<div class="tools-right f-r">
      		
			      <div class="search-wrap" style="display: inline-block;">
              <el-input placeholder="请输入关键词" v-model="query.keywords">
                <template slot="append">
                  <i class="icon el-icon-search"></i>
                </template>
              </el-input>
            </div>
			
      	</div>
    </div> -->
    <el-row>
    	<el-col :span="4">
    		<div class="grid-content">
    			<div class="content-side-nav-wrap">
    				
    				<ul class="side-nav">
    					<li 
    						class="nav-item"
    						v-for="(nav,index) in deviceNav"
    						:key="index"
    						:class="{'current': nav.current}"
    						@click="deviceNavClick(nav)"
    					>{{nav.name}}</li>
    					
    				</ul>

    			</div>
    		</div>
    	</el-col>

  		<el-col :span="20">
  			<div class="grid-content">
  				

  				<!-- 内容栏--表格 -->
			    <div class="content-table-wrap" v-loading="loading" loading-type="chrome-circle-turn" :style="{height:ResultHeight+'px'}">

			    	<el-table
				        border
				        v-if="data"
				        size="small"
				        :data="data"
				        :height.sync="tableHeight"
				        :header-cell-style="{background:'#42b983',color:'#ffffff'}"
				        :cell-style="{borderWidth:0}"
				        style="width: 100%"
			      	>
			    		
			        <el-table-column
				        fixed
				        prop="id"
				        label="ID"
				        width="120">
			        </el-table-column>

		    		<el-table-column
				      	prop="deviceNo"
				      	label="设备编号"
				      	width="150">
				    </el-table-column>

			        <el-table-column
			          	prop="data"
			          	label="数据"
			        >

			          	<template slot-scope="scope">
				            <div>
				              {{ getDeviceData(scope.row) }}
				            </div>
          				</template>

			        </el-table-column>

				    <el-table-column
			          	prop="createTime"
			          	label="接收时间"
			          	width="150">
			        </el-table-column>

			    </el-table> 

			      <!-- 分页 -->
			      <div ref="adminContentPagination" class="content-pagination-wrap">
			        <el-pagination
			            background
			            :current-page="page.currentPage"
			            :page-sizes="pageSizes"
			            :page-size="page.pageSize"
			            layout="total, sizes, prev, pager, next, jumper"
			            :total="page.total"
			            @current-change="currentPageChange"
			        >
			        </el-pagination>
			      </div> 
			    </div>

  			</div>
  		</el-col>

    </el-row>



    

    <!-- 修改dialog -->
    <edit-dialog
    	:visible="editDialogVisible"
    	:form.sync='editForm'
      :type="editType"
    	@cancel="editDialogCancel"
      @confirm="editDialogConfirm"
    ></edit-dialog>

  </div>

</template>

<script>
import { mapGetters } from 'vuex'

import {
  list as deviceList
} from "@/api/equipment/equipment";

import { list } from "@/api/data/history";

import editDialog from '@/components/agriculture/equipment/editDialog.vue'  

import adminMixins from "@/mixins/admin"
export default {
  name: 'role',
  mixins:[adminMixins],
  components:{
  	editDialog,
  },
  computed: {
    ...mapGetters([
      'name',
      'permission',
      'userInfo'
    ])
  },
  data(){
  	return{
      query:{
        keywords:''
      },
      deviceNo:'',
      deviceNav:[],
      //1新增，2修改
      editType:1,
      loading:true,
  		//修改模态框的显示隐藏
  		editDialogVisible:false,
  		data:null,
      testData:[
        {
          id:"334995096",
          number:"73F15233E6F3",
          online:'在线',
          name:"山东师范农场采集设备2",
          acquisitionTime:"2019-12-19 16:34:49",
          data:'18 ℃ | 36.4 %RH | 3767.9 ℃ | 16.3 %RH ',
        }
      ],
  		page: {
    	  pageSize: 10,
    	  currentPage: 1,
    	  total: 0
  	  },
  	  pageSizes:[10,20,30,40,50,100],
  	  editForm:null
  	}
  },
  mounted(){
    //设置dom尺寸
    this.setSize();
  	//this.loadData(this.page)
  	this.deviceList();
  },
  methods:{
  	//获取设备列表并请求历史数据
  	deviceList(){
  		deviceList(1,9999,{}).then(res => {
  			const result = res.data.data.records;
  			result.forEach((item,index) => { 
  				if(index === 0){
  					item["current"] = true;
  					this.deviceNo = item.deviceNo;
  				}else{
  					item["current"] = false;
  				}
  			})
  			this.deviceNav = result;

  			//请求历史数据
  			this.loadData(this.page)
  		})
  	},
  	//设备切换
  	deviceNavClick(item){
  		if(item.deviceNo === this.deviceNo) return;
  		//更新设备号
  		this.deviceNo = item.deviceNo;
  		//更新当前表示状态
  		this.deviceNav.forEach((item) => {
  			if(item.deviceNo === this.deviceNo){
  				item['current'] = true;
  			}else{
  				item['current'] = false;
  			}
  		})
  		//重置当前页
  		this.page.currentPage = 1;
  		//请求数据
  		this.loadData(this.page);
  	},
  	//请求table数据
  	loadData(page, params = {}){
  		this.loading = true;
      	list(this.deviceNo, page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {

        	this.loading = false;
        	console.log("--------历史数据--------")
        	console.log(res)
          	const result = res.data.data.records;
          
          	this.page.currentPage = res.data.data.current;
          	this.page.total = res.data.data.total;
        	this.data = this.convertData(result);

          	//this.data = this.testData;
      	});
      	
  	},
  	//页面改变
  	currentPageChange(val){
  		this.page.currentPage = val;
  		//请求数据
  		this.loadData(this.page);
  	},
  	//获取单条设备数据
  	getDeviceData(row){
  		var arr = [];
  		//空气湿度
  		if(row.airHumidity){
  			arr.push("空气湿度："+row.airHumidity)
  		};
  		//空气温度
  		if(row.airTemperature){
  			arr.push("空气温度："+row.airTemperature)
  		};
  		//土壤电导率
  		if(row.soilConductivity){
  			arr.push("土壤电导率："+row.soilConductivity)
  		};
  		//土壤湿度
  		if(row.soilMoisture){
  			arr.push("土壤湿度："+row.soilMoisture)
  		};
  		//土壤温度
  		if(row.soilTemperature){
  			arr.push("土壤温度："+row.soilTemperature)
  		};
  		//光照
  		if(row.sunlight){
  			arr.push("光照："+row.sunlight)
  		}


  		//继电器相关
  		if(String(row.status1)){
  			row.status1 == 1 ? arr.push("继电器1：开") : arr.push("继电器1：关")
  		}

  		if(String(row.status2)){
  			row.status2 == 1 ? arr.push("继电器2：开") : arr.push("继电器2：关")
  		}

  		if(String(row.status3)){
  			row.status3 == 1 ? arr.push("继电器3：开") : arr.push("继电器3：关")
  		}

  		if(String(row.status4)){
  			row.status4 == 1 ? arr.push("继电器4：开") : arr.push("继电器4：关")
  		}

  		if(arr.length){
  			return arr.join('|')
  		}

  		return '';
  	},
    convertData(data){

      return data;
    },

    //新增
    handleAdd(){
        this.editForm = null;
        this.editType = 1;
        //模态框显示
        this.editDialogVisible = true;
    },
    //刷新当前页
    refresh(){
      this.loadData(this.page)
    },
  	//点击操作的编辑
  	handleEdit(row){
  		this.editType = 2;
      this.editForm = row;
      //模态框显示
      this.editDialogVisible = true;
      
  	},
  	//点击操作的删除
  	handleDel(row){
  		console.log(row)

  		this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
          	confirmButtonText: '确定',
          	cancelButtonText: '取消',
          	type: 'warning'
        }).then(()=>{
        	return del(row.id);
        }).then((res) => {

        	this.loadData(this.page)
          	this.$message({
            	type: 'success',
            	message: '删除成功!'
          	});
        }).catch(() => {
          	this.$message({
            	type: 'info',
            	message: '已取消删除'
          	});          
        });
  	},
  	//取消
  	editDialogCancel(){
  		this.editDialogVisible = false;
  		this.editForm = null;
  	},
    //确认
    editDialogConfirm(form){
      this.editDialogVisible = false;

      edit(form.data).then((res)=>{

        //this.editDialogVisible = false;
        this.loadData(this.page)
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
      })

      
    },
  }
}
</script>

<style lang="scss" scoped>
.content {
  &-container {

  }
  /***搜索栏***/
  &-search-wrap{
    padding: 15px;
    border-bottom: 1px solid #E8EBEE;
  }
  /***工具栏***/
  &-tools-wrap{
    padding: 15px;
  }
  &-side-nav-wrap{
  	padding: 15px;

  	.side-nav{
  		list-style: none;
  		padding-left: 0;
  		margin: 0;
  		.nav-item{
  			text-align: left;
  			padding: 15px 10px;
  			margin-bottom: 5px;
  			background: #eaeaea;
  			&.current{
  				background: #42b983;
  				color: #ffffff;
  				font-weight: 700;
  			}
  		}
  	}
  }
  /***内容栏***/
  &-table-wrap{
    position: relative;
    padding: 15px;
    .cell{
      .icon{
        margin-right: 10px;
      }
    }
  }
  /***分页***/
  &-pagination-wrap{
    text-align: right;
  	padding-top: 15px;
  }
}
</style>
